package com.usefullc.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.system.domain.SerialNumber;
import com.usefullc.system.mapper.SerialNumberMapper;
import com.usefullc.system.query.BaseQuery;
import com.usefullc.system.query.SerialNumberQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author: Sampson
 * @date: 2022-04-16 17:15
 */
@Service
public class SerialNumberService extends AbstractBizService<SerialNumberMapper,SerialNumber,SerialNumberQuery> {

    @Autowired
    private SerialNumberMapper serialNumberMapper;


    @Transactional
    public String getSerialNumber(String tableName, String type) {
        SerialNumberQuery query = new SerialNumberQuery();
        query.setTableName(tableName);
        query.setType(type);
        Integer newNo = 1;
        SerialNumber serialNumber = this.findOne(query);
        if (serialNumber == null) {
            serialNumber = new SerialNumber();
            serialNumber.setTableName(tableName);
            serialNumber.setType(type);
            serialNumber.setNo(newNo);
            try {
                this.save(serialNumber);
            } catch (Exception e) {
                //约束异常，重新获取
                return getSerialNumber(tableName, type);
            }
        } else {
            serialNumberMapper.incrNo(serialNumber.getId());
            newNo = serialNumber.getNo() + 1;
        }
        String parent = "";
        if (!type.equalsIgnoreCase("0")) {
            parent = type;
        }
        String resultNo = parent + StringUtils.leftPad(newNo.toString(), 4, '0');
        return resultNo;

    }

    @Override
    public QueryWrapper<SerialNumber> getQueryWrapper(SerialNumberQuery query) {
        QueryWrapper<SerialNumber> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }
}
